package halilTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Vector;

public class NodeH {
	
	private int PORT;
	
	private BufferedReader br;
	private String range;
	private DatagramSocket socket;
	private Vector<String> messages;
	private Thread reciever;
	
	

	public NodeH(){
		try {
			socket = new DatagramSocket(0, InetAddress.getLocalHost()); // Init server soket
			PORT = socket.getLocalPort();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		reciever = new Thread(new NodeReciever(this));
		messages = new Vector<String>();
	}
	public void comm(){
		String message = "NODE,NEW," + socket.getLocalAddress()+":"+PORT+"," + "porukaaaaaaa";
		byte[] sendData = message.getBytes(); 
		try {
			DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getLocalHost(), SystemInfo.BS_PORT);
			socket.send(sendPacket);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public DatagramSocket getSocket() {
		return socket;
	}
	public void addMessage(String message){
		this.messages.add(message);
		System.out.println("NODE RECIEVED: " + message);
	}
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("Node info: ");
		sb.append('\n');
		sb.append("    Address: " + socket.getLocalAddress() + ":" + socket.getLocalPort() + '\n');
		return sb.toString();
	}
	
	public static void main(String[] args) {
		NodeH n = new NodeH();
		System.out.println(n);
		n.reciever.start();
		n.comm();
		
	}
}
